from wsgiref.simple_server import make_server
# 引入结束http协议的服务器（wsgiref）
import time

# 4. VIEW 试图函数 处理不同的路由对应的函数

def foo1(req):
    with open('index1.html','rb') as f:
        data=f.read()
    return data

def foo2(req):
    with open('index2.html','rb') as f:
        data =f.read()
        print('---------')
        print(data)
        print('---------')
    return data

def login(req):
    with open('login.html','rb') as f:
        data=f.read()
    return data

def sigup(req):
    pass

def showtime(req):
    # 2. mode  M数据库中取数据 取出来后转成一个变量
    times=time.ctime()
    print(time,type(times))
    # return ('<h1>time:%s</h1>'% str(times)).encode('utf8')
    with open('showtime.html','rb') as f :
        data=f.read()
        data=data.decode('utf8')

        # 3.T 替换模板渲染  前端展示
        data=data.replace('@@time@@',times)
    return data.encode('utf8')
def router():
    # 1. 控制器 -----路由分发----------
    url_patterns=[
        ('/login',login),
        ('/sigup',sigup),
        ('/alex',foo1),
        ("/bob",foo2),
        ("/showtime",showtime)
    ]
    return url_patterns

def applications(environ,start_response):
    print(environ['PATH_INFO'])
    path=environ['PATH_INFO']
    start_response('200 OK', [('Content-Type', 'text/html'),('Charset', 'utf8')])
    # print(environ)
    func=None
    url_patterns=router()
    for item in url_patterns:
        if item[0]==path:
            func=item[1]
            # print(item)
            break
    if func:
        return [func(environ)]
    else:
        return [b'404']

httpd = make_server('',8080,applications)

print("server HTTP ON PORT 8080......")
httpd.serve_forever()